package com.py.credit.service.impl;

import com.py.credit.entity.LhjcBatchFile;
import com.py.credit.entity.LhjcBatchLog;
import com.py.credit.entity.LhjcCube;
import com.py.credit.entity.common.LogEnum;
import com.py.credit.service.*;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lufl 未完成日志处理
 */
@Component
public class LhjcUntreatedFileShedule {

    private static final Logger LOG = Logger.getLogger(LhjcUntreatedFileShedule.class);

    @Autowired
    private LhjcBatchLogService lhjcBatchLogService;

    @Autowired
    private LhjcExcelReadService lhjcExcelReadService;

    @Autowired
    private LhjcStepLogService lhjcStepLogService;

    @Autowired
    private LhjcWriteLogsService lhjcWriteLogsService;

    @Autowired
    private LhjcDataCheckService lhjcDataCheckService;

    @Autowired
    private LhjcDataInsertService lhjcDataInsertService;

    public synchronized void run(String absolutepath) {
        LhjcBatchFile batchFile = null;
        try {
            List<LhjcBatchFile> list = lhjcBatchLogService.getUntreatedFiles();
            if (list != null && list.size() > 0) {
                batchFile = list.get(0);

                // 讲文件状态标识为处理中
                lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.CLZ);
                // 处理流程日志
                lhjcStepLogService.add(batchFile.getBatchId(), "开始处理上传文件。");
                // 获取虚拟表信息
                LhjcBatchLog batchLog = lhjcBatchLogService.select(batchFile.getBatchId());

                LhjcCube cube = lhjcBatchLogService.queryCubeById(batchFile.getTableId());

                StringBuilder filePath = new StringBuilder(200);
                filePath.append(absolutepath);
                filePath.append(File.separator + "upload");
                filePath.append(batchFile.getFpath());
                filePath.append(batchFile.getFname());

                lhjcStepLogService.add(batchFile.getBatchId(), "解析上传的EXCEL文件。");

                Sheet st = lhjcExcelReadService.readExcelFileForSheet(filePath.toString());
                Map<String, Object> map = lhjcExcelReadService.readExcelFileHead(st, batchFile.getBatchId(),
                        cube.getListMetric());
                if (map == null || map.isEmpty()) {
                    Map<String, Object> resultMap = readExcelData(absolutepath, batchFile.getBatchId(), st, cube, batchLog);

                    int totalCount = (int) resultMap.get("totalCount");

                    int totalDuplicationCount = (int) resultMap.get("totalDuplicationCount");
                    int totalMissCount = (int) resultMap.get("totalMissCount");
                    int totalDeptErrorCount = (int) resultMap.get("totalDeptErrorCount");
//					int totalLyErrorCount = (int) resultMap.get("totalLyErrorCount");

                    int errorCount = (int) resultMap.get("errorCount");

                    if (totalCount == 0) {

                        lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.EX_RESULT_F, totalCount, 0, 0, 0,
                                LogEnum.YWC);

                    } else if (totalMissCount > 0 || totalDuplicationCount > 0 || totalDeptErrorCount > 0) {

                        if (totalMissCount + totalDuplicationCount + totalDeptErrorCount == totalCount) {

                            lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.EX_RESULT_F, totalCount, 0,
                                    totalDeptErrorCount + totalMissCount, totalDuplicationCount, LogEnum.YWC);

                        } else {

                            lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.EX_RESULT_P, totalCount,
                                    totalCount - totalDuplicationCount - totalDeptErrorCount - totalMissCount, totalDeptErrorCount + totalMissCount, totalDuplicationCount,
                                    LogEnum.YWC);
                        }

                    } else {

                        lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.EX_RESULT_S, totalCount, totalCount, 0,
                                0, LogEnum.YWC);
                    }

                } else {
                    lhjcWriteLogsService.writeLogFile(absolutepath, batchFile.getBatchId(), map.get("ERROR_MESS").toString());
                    // 记录错误日志
                    lhjcStepLogService.add(batchFile.getBatchId(), "数据有错误: 详情请查阅日志。");
                    // //处理未结束写状态
                    lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.EX_RESULT_F, 0, 0, 0, 0, LogEnum.YWC);
                }
            }
        } catch (Exception e) {

            lhjcBatchLogService.modify(batchFile.getBatchId(), LogEnum.EX_RESULT_F, 0, 0, 0, 0, LogEnum.YWC);
            lhjcWriteLogsService.writeLogFile(absolutepath, batchFile.getBatchId(), "系统异常，请联系管理员");
            e.printStackTrace();

        }
    }

    private Map<String, Object> readExcelData(String absolutepath, String batchId, Sheet st, LhjcCube cube, LhjcBatchLog batchLog)
            throws IOException {
        boolean reStart = true;
        int i = 0;
        List<Map<String, Object>> listDataMap = null;
        int totalCount = 0;
        int totalDuplicationCount = 0;
        int totalMissCount = 0;
        int totalDeptErrorCount = 0;
//		int totalLyErrorCount = 0;
        Map<String, Object> checkResultMap = null;
        // 获取错误信息
        String errorMess = null;
        int errorCount = 0;
        int start = 0;
        int end = 0;
        Map<String, Object> resultMap = new HashMap<>();
        while (reStart) {
            start = i * 1000;
            end = (i + 1) * 1000;
            if (end > st.getLastRowNum()) {
                end = st.getLastRowNum();
            }

            // 获取相对目录的路径
            listDataMap = lhjcExcelReadService.readExcelData(start, end, st, batchId, cube.getListMetric(), cube.getCubeId());

            int size = listDataMap.size();
            if (listDataMap.isEmpty() && i == 0) {
                lhjcWriteLogsService.writeLogFile(absolutepath, batchId, "上传文件数据不得为空");
                reStart = false;
            } else if (listDataMap.isEmpty()) {
                reStart = false;
            } else {
                // 处理流程日志
                lhjcStepLogService.add(batchId, "解析上传的Excel的" + start + "到" + end + "行数据。");

                // 校验
                lhjcStepLogService.add(batchId, "开始数据校验：" + start + "到" + end + "行数据。");
//				Map<String, Object> duplicationCheck = inspectDataStyleService.duplicationCheck(listDataMap, cube);
                Map<String, Object> duplicationCheck = new HashMap<String, Object>();

                //判断选哪种校验规则
                if (cube.getCubeId() == 1005 || cube.getCubeId() == 1007) {
                    //duplicationCheck = lhjcDataCheckService.duplicationFileFrCheck(listDataMap, cube,batchLog);
                } else if (cube.getCubeId() == 1006 || cube.getCubeId() == 1008) {
                    //duplicationCheck = lhjcDataCheckService.duplicationFileZrrCheck(listDataMap,cube,batchLog);
                } else {
                    duplicationCheck = lhjcDataCheckService.duplicationCheck(listDataMap, cube);
                }

                String duplicationMess = (String) duplicationCheck.get("duplicationMess");
                int duplicationCount = (int) duplicationCheck.get("duplicationCount");
                String missMess = (String) duplicationCheck.get("missMess");
                int missCount = (int) duplicationCheck.get("missCount");
                String deptErrorMess = (String) duplicationCheck.get("deptErrorMess");
                int deptErrorCount = (int) duplicationCheck.get("deptErrorCount");
                String lyErrorMess = (String) duplicationCheck.get("lyErrorMess");
//				int lyErrorCount = (int) duplicationCheck.get("lyErrorCount");

                if (duplicationCount != 0) {

                    totalDuplicationCount += duplicationCount;
                    lhjcWriteLogsService.writeLogFile(absolutepath, batchId, duplicationMess);
                }

                if (missCount != 0) {
                    totalMissCount += missCount;
                    lhjcWriteLogsService.writeLogFile(absolutepath, batchId, missMess);
                }

                if (deptErrorCount != 0) {
                    totalDeptErrorCount += deptErrorCount;
                    lhjcWriteLogsService.writeLogFile(absolutepath, batchId, deptErrorMess);
                }

//				if(lyErrorCount != 0){
//					totalLyErrorCount += lyErrorCount;
//					writeLogsService.writeLogFile(batchId, lyErrorMess);
//				}

                lhjcStepLogService.add(batchId, "开始将Excel" + start + "到" + end + "行数据录入至清洗库。");

                //判断选哪种写入数据库方式
                if (cube.getCubeId() == 1005 || cube.getCubeId() == 1007) {
                    //dataInsertService.addFrData(listDataMap,cube,batchId,(Date) duplicationCheck.get("now"),batchLog);
                } else if (cube.getCubeId() == 1006 || cube.getCubeId() == 1008) {
                    //dataInsertService.addZrrData(listDataMap,cube,batchId,(Date) duplicationCheck.get("now"),batchLog);
                } else {
                    lhjcDataInsertService.addData(listDataMap, cube, batchId);
                }

//				zooService.addZooData(listDataMap, cube, batchId);

                lhjcStepLogService.add(batchId, "结束将Excel" + start + "到" + end + "行数据录入至清洗库。");

                totalCount += size;

            }

            i++;
        }
        // 数据总量
        resultMap.put("totalCount", totalCount);
        // 重复数量
        resultMap.put("totalDuplicationCount", totalDuplicationCount);
        // 缺失数量
        resultMap.put("totalMissCount", totalMissCount);
        // 部门数据错误数量
        resultMap.put("totalDeptErrorCount", totalDeptErrorCount);
        // 未通过校验数量
        resultMap.put("errorCount", errorCount);
        return resultMap;

    }

}
